<template>
  <BaseMainSlot>
    <template v-slot:searchbox>
      <div class="seach-box">
        <div class="select-box-content">
          <div class="select-box-content-name">计划名称：</div>
          <el-input
            v-model="planName"
            clearable
            placeholder="请输入计划名称"
            @change="queryPageList()"
          />
        </div>

        <!-- <div class="select-box-content">
          <div class="select-box-content-name">是否过期：</div>
          <div
            class="select-box-content-all"
            @click="cancelSelect('whetherOverdue')"
          >全部</div>
          <div
            v-for="(item, index) in pastList"
            :key="index"
            class="select-box-content-list"
            :style="{ color: whetherOverdue === item.id ? '#54DEE2' : '#C1CFD2' ,fontWeight : whetherOverdue === item.id ? '600':'400' }"
            @click="selectOverdue(item.id)"
          >{{ item.name }}</div>
        </div>-->
        <div class="select-box-content">
          <div class="select-box-content-name">有效日期</div>
          <el-date-picker
            v-model="startTime"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="yyyy-MM-dd HH:mm:ss"
            @change="queryPageList()"
          />
        </div>
      </div>
    </template>
    <template v-slot:btnsBar>
      <ActionBar
        :add-active="addActive"
        :del-active="delActive"
        :page-no="153"
        @add="add"
        @del="del"
      />
    </template>
    <template v-slot:content>
      <e-table
        ref="tableData"
        rowKey="planId"
        :table-data="tableData"
        :table-columns="tableLabel"
        :page="currentPage"
        :size="pageSize"
        :total="totalSize"
        :loading="loading"
        :table-option="tableOption"
        @sizeChange="changePageSize"
        @pageChange="changeCurrentPage"
        @tableUpdatePlus="mixTableUpdatePlus"
        @handleSelectionChange="handleSelectionChange"
      >
        <template
          v-if="scoped.row.planId"
          slot="generateHour"
          slot-scope="scoped"
        >{{ changeTime(scoped.row.generateHour) }}</template>
        <!--  <template v-if="scoped.row.planId" slot="status" slot-scope="scoped">
          <span
            v-if="scoped.row.status===true"
            style="color:#1be574;font-weight:700;"
          >启用中</span>
          <span
            v-else-if="scoped.row.status===false"
            style="color:#e32d2d;font-weight:700;"
          >停用中</span>
          <span v-else>暂未获取状态</span>
        </template>-->
        <template
          v-if="scoped.row.planId"
          slot="operate_status"
          slot-scope="scoped"
        >
          <el-switch
            v-if="judgePermission(153,'stop')||judgePermission(153,'start')"
            v-model="scoped.row.operate_status"
            active-color="#13ce66"
            inactive-color="#ff4949"
            @change="changeStatus(scoped.row)"
          />
        </template>
        <template slot="startTime" slot-scope="scoped" v-if="scoped.row.planId">
          <span>
            {{ scoped.row.startTime?scoped.row.startTime:'' }}
            <span
              v-if="scoped.row.startTime&&scoped.row.endTime"
            >至</span>
            {{ scoped.row.endTime?scoped.row.endTime:'' }}
          </span>
        </template>
        <template slot="operate" v-if="scoped.row.planId" slot-scope="scoped">
          <span
            v-if="judgePermission(153,'edit')"
            class="table-btns-box"
            @click="edit(scoped.row)"
          >
            <i class="el-icon-edit-outline"></i>
            <span>修改</span>
          </span>

          <span
            v-if="judgePermission(153,'deleteone')"
            class="table-btns-box table_del_btn"
            @click="delOne(scoped.row)"
          >
            <i class="el-icon-delete"></i>
            <span>删除</span>
          </span>
        </template>
      </e-table>
      <AddEditDialog
        ref="addEditDialog"
        :now-chance-stau="nowChanceStau"
        :title-text="titleText"
        :edit-object="editObject"
        :show.sync="showAddEditDialog"
        @closeDialog="closeDialog"
        @cancelDialog="cancel"
      />
      <MessageDialog
        ref="MessageDialog"
        :show.sync="showChangeStatusDialog"
        :message="messageTitle"
        :edit-object="editObject"
        :title-text="titleText"
        @save="save"
        @closeDialog="closeDialog"
        @cancelDialog="cancel"
      />
    </template>
  </BaseMainSlot>
</template>

<script>
import ActionBar from "@/components/ActionBar";
import maintenancePlanApi from "@/api/equip-maintenance-manage/maintenance-plan";
import BaseMainSlot from "@/components/BaseMainSlot/kong-new.vue";
import AddEditDialog from "./components/add-edit-dialog.vue";
import { mymixin } from "@/utils/mixin";
import { maintenanceMixins } from "@/utils/maintenance-mixins";
import MessageDialog from "@/components/detailDialog/message-dialog.vue";
import { mapGetters } from "vuex";
export default {
  name: "MaintenancePlan",
  components: {
    ActionBar,
    BaseMainSlot,
    AddEditDialog,
    MessageDialog,
  },
  mixins: [mymixin, maintenanceMixins],
  data() {
    return {
      // 控制弹出框显示隐藏
      showAddEditDialog: false,
      // 搜索条件:保养计划名称：
      planName: "",
      startTime: [],
      //  搜索条件:是否过期：：
      whetherOverdue: "",
      pastList: [
        { name: "已过期", id: true },
        { name: "未过期", id: false },
      ],
      checkedIdList: [],
      // 改变计划启停
      showChangeStatusDialog: false,
      messageTitle: "",
      generateHourList: [
        { generateHourId: 0, generateHourName: "00:00:00" },
        { generateHourId: 1, generateHourName: "01:00:00" },
        { generateHourId: 2, generateHourName: "02:00:00" },
        { generateHourId: 3, generateHourName: "03:00:00" },
        { generateHourId: 4, generateHourName: "04:00:00" },
        { generateHourId: 5, generateHourName: "05:00:00" },
        { generateHourId: 6, generateHourName: "06:00:00" },
        { generateHourId: 7, generateHourName: "07:00:00" },
        { generateHourId: 8, generateHourName: "08:00:00" },
        { generateHourId: 9, generateHourName: "09:00:00" },
        { generateHourId: 10, generateHourName: "10:00:00" },
        { generateHourId: 11, generateHourName: "11:00:00" },
        { generateHourId: 12, generateHourName: "12:00:00" },
        { generateHourId: 13, generateHourName: "13:00:00" },
        { generateHourId: 14, generateHourName: "14:00:00" },
        { generateHourId: 15, generateHourName: "15:00:00" },
        { generateHourId: 16, generateHourName: "16:00:00" },
        { generateHourId: 17, generateHourName: "17:00:00" },
        { generateHourId: 18, generateHourName: "18:00:00" },
        { generateHourId: 19, generateHourName: "19:00:00" },
        { generateHourId: 20, generateHourName: "20:00:00" },
        { generateHourId: 21, generateHourName: "21:00:00" },
        { generateHourId: 22, generateHourName: "22:00:00" },
        { generateHourId: 23, generateHourName: "23:00:00" },
      ],
      // 表单展示项
      tableLabel: [
        {
          label: "保养计划名称",
          param: "planName",
          show: true,
        },
        // {
        //   label: "状态",
        //   param: "status",
        //   show: true,
        //   slotName: "status",
        //   notSearch: true,
        // },
        {
          label: "任务启停",
          param: "operate_status",
          show: true,
          slotName: "operate_status",
          notSearch: true,
        },
        {
          label: "计划有效时间",
          param: "startTime",
          show: true,
          type: "datetime_range",
          slotName: "startTime",
          notSearch: true,
        },
        {
          label: "任务自动生成时间",
          param: "generateHour",
          show: true,
          slotName: "generateHour",
          notSearch: true,
        },
      ],
      // 表单事件
      tableOption: {
        label: "操作",
        options: [
          {
            label: "操作",
            slotName: "operate",
          },
        ],
      },
    };
  },
  computed: {
    ...mapGetters({
      judgePermission: "permission/judgePermission",
    }),
  },
  watch: {},
  created() {
    this.queryPageList();
  },
  mounted() {},
  methods: {
    // 清空选项
    cancelSelect(data) {
      if (data === "whetherOverdue") {
        this.whetherOverdue = "";
      }
      this.queryPageList();
    },
    // 选择
    selectOverdue(id) {
      if (this.whetherOverdue === id) {
        this.whetherOverdue = "";
      } else {
        this.whetherOverdue = id;
      }
      this.queryPageList();
    },
    // 转换时间
    changeTime(item) {
      let data = "";
      var index = this.generateHourList.findIndex(
        (a) => a.generateHourId === item
      );
      if (index !== -1) {
        data = this.generateHourList[index]["generateHourName"];
      }
      return data;
    },
    queryPageList(e) {
      this.loading = false;
      // 获取数据
      let param = {
        page: this.currentPage,
        size: this.pageSize,
        ...e,
      };
      if (this.planName || e?.planName) {
        param["planName"] = this.planName || e?.planName;
      } else {
        delete param["planName"];
      }
      // if (this.whetherOverdue) {
      //   param["whetherOverdue"] = this.whetherOverdue;
      // }
      if (this.startTime.length == 2) {
        param["startTime"] = this.startTime[0];
        param["endTime"] = this.startTime[1];
      }
      maintenancePlanApi.queryPageList(param).then((res) => {
        this.loading = false;
        if (res.code === 1) {
          let data = res.data;
          this.totalSize = data.total;
          data.list.forEach((item) => {
            item["operate_status"] = item.status;
          });
          this.tableData = data.list;
          this.addblankmet();
          this.resetActionBar();
        }
      });
    },
    handleSelectionChange(list) {
      if (list.length == 0) {
        this.delActive = false;
        return;
      }
      this.checkedIdList = [];
      let emptyList = [];
      list.forEach((item) => {
        if (item.planId) {
          this.checkedIdList.push(item.planId);
        } else {
          emptyList.push(item);
        }
      });

      if (this.checkedIdList.length >= 1) {
        this.delActive = true;
      } else {
        this.delActive = false;
        this.$message.warning("不可选择空数据！");
      }
      if (list.length === emptyList.length) {
        this.toggleNoSelection();
      } else {
        this.toggleNoSelection(emptyList);
      }
    },
    //状态变更,点击的时候，list里的operate_status状态已经改变，需要通过status改变成之前的状态
    resetSwitchStatus(data) {
      this.tableData.forEach((item) => {
        if (item.equipmentCode === data.equipmentCode) {
          item.operate_status = item.status;
          console.log("start11", item);
          return;
        }
      });
    },
    //状态变更,点击的时候，list里的operate_status状态已经改变，需要通过status改变成之前的状态
    changeStatus(data) {
      console.log("changeStatus", data.status);
      if (data.status === true) {
        this.stop(data);
      } else {
        this.start(data);
      }
    },
    // 启用计划
    start(row) {
      this.resetSwitchStatus(row);
      this.editObject = JSON.parse(JSON.stringify(row));
      this.titleText = "计划启用";
      this.messageTitle = "确认是否启用该计划？";
      this.showChangeStatusDialog = true;
    },
    // 停用计划
    stop(row) {
      this.resetSwitchStatus(row);
      this.editObject = JSON.parse(JSON.stringify(row));
      this.titleText = "计划停用";
      this.messageTitle = "确认是否停用该计划？";
      this.showChangeStatusDialog = true;
    },
    // 启停计划
    save(data) {
      var params = {};
      if (this.messageTitle === "确认是否启用该计划？") {
        params = { planId: data["planId"], status: true };
      }
      if (this.messageTitle === "确认是否停用该计划？") {
        params = { planId: data["planId"], status: false };
      }
      maintenancePlanApi.edit(params).then((res) => {
        if (res.code === 1) {
          this.$message.success(res.msg);
          this.closeDialog();
        } else {
          this.$message.error(res.msg);
        }
      });
    },
    // 单个删除
    delOne(data) {
      this.$confirm("此操作将永久删除该项, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        customClass: "myClass",
      })
        .then(() => {
          maintenancePlanApi
            .delList({ planIdList: [data.planId] })
            .then((res) => {
              if (res.code === 1) {
                this.$message.success(res.msg);
                this.queryPageList();
                this.resetActionBar();
              }
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    // 表格删除
    delmessage() {
      maintenancePlanApi
        .delList({ planIdList: this.checkedIdList })
        .then((res) => {
          if (res.code === 1) {
            this.$message.success(res.msg);
            this.queryPageList();
            this.resetActionBar();
          }
        });
    },
    // 添加
    add() {
      this.nowChanceStau = "add";
      this.titleText = "添加";
      this.addActive = false;
      this.delActive = false;
      this.showAddEditDialog = true;
    },
    // 修改
    edit(row) {
      if (row.planId) {
        this.editObject = JSON.parse(JSON.stringify(row));
        this.nowChanceStau = "edit";
        this.titleText = "修改";
        this.addActive = false;
        this.delActive = false;
        this.showAddEditDialog = true;
      } else {
        this.editObject = {};
      }
    },
    closeDialog() {
      this.showAddEditDialog = false;
      this.showChangeStatusDialog = false;
      this.nowChanceStau = "";
      this.titleText = "";
      this.editObject = {};
      this.addActive = true;
      this.delActive = false;
      // this.$refs.tableData.setCurrentRow();
      // this.$refs.tableData.clearSelection();
      this.queryPageList();
    },
    cancel() {
      this.showAddEditDialog = false;
      this.showChangeStatusDialog = false;
      this.nowChanceStau = "";
      this.titleText = "";
      this.editObject = {};
      this.addActive = true;
      this.delActive = false;
      // this.$refs.tableData.setCurrentRow();
      //this.$refs.tableData.clearSelection();
    },
  },
};
</script>

<style lang="scss" scoped>
::v-deep .el-switch__label.is-active {
  color: #fff;
}
::v-deep .el-switch__label--right {
  color: #fff;
}
::v-deep .el-switch__label--left {
  color: #fff;
}
</style>
